package org.springframework.extcache.localcache;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

public class ConcurrentMapCacheManagerFactoryBean
    implements FactoryBean<ConcurrentMapCacheManager>, DisposableBean, InitializingBean {

  private ConcurrentMapCacheManager     cacheManager;
  private int                           maxSize;
  private ConcurrentMap<String, Object> store;
  private int                           expireTime;

  public void setMaxSize(int maxSize) {
    this.maxSize = maxSize;
  }

  public void setExpireTime(int expireTime) {
    this.expireTime = expireTime;
  }

  @Override
  public ConcurrentMapCacheManager getObject() throws Exception {
    if (cacheManager == null) {
      store = new ConcurrentHashMap<String, Object>(256);
      cacheManager = new ConcurrentMapCacheManager(store, maxSize);
      cacheManager.setExpireTime(expireTime);
    }
    return cacheManager;
  }

  @Override
  public Class<?> getObjectType() {
    return ConcurrentMapCacheManager.class;
  }

  @Override
  public boolean isSingleton() {
    return true;
  }

  @Override
  public void destroy() throws Exception {
    if (store != null) {
      store.clear();
    }
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    Assert.isTrue(maxSize > 0, "maxSize was not configured!!!");
    Assert.isTrue(expireTime > 0, "expireTime was not configured!!!");
  }

}
